package leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: feiwang_6
 * @create: 2020/4/13 22:49
 * @description:
 */
public class ZString {
    
    @Test
    public void testZString(){
        String str = "AB";
        int rowNum = 1;
        System.out.println(convertZStr(str, rowNum));
    }
    
    public String convertZStr(String str, int rowNum){
        if("".equals(str) || str.length() == 1 || rowNum == 1){
            return str;
        }
        List<StringBuffer> list = new ArrayList<>(rowNum);
        for(int i = 0; i < rowNum; i++){
            list.add(new StringBuffer());
        }
        boolean downFlag = true;
        int cur = 0;
        char[] chars = str.toCharArray();
        for(char c : chars){
            //向下
            if(downFlag){
                list.get(cur).append(c);
                cur++;
                if(cur == rowNum){
                    downFlag = false;
                    cur--;
                }
            }else {
                //向上
                cur--;
                list.get(cur).append(c);
                if(cur == 0){
                    downFlag = true;
                    cur++;
                }
            }
        }
        StringBuffer buffer = new StringBuffer(str.length());
        for(StringBuffer b : list){
            buffer.append(b.toString());
        }
        return buffer.toString();
    }
}
